<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    // 深拷贝
    function deepClone(obj = {}) {
      if (typeof obj !== 'object' || obj == null) {
        // obj是null或者不是对象和数组，直接返回
        return obj
      }

      // 初始化返回结果
      let result = []
      if (obj instanceof Array) {
        result = []
      } else {
        result = {}
      }

      // 遍历
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          result[key] = deepClone(obj[key])
        }
      }

      return result
    }
    const obj = {
      name: 'zhangsna',
      child: {
        name: 'lisi',
        child: {
          name: 'wangwu'
        }
      },
      cars: ['xxx', 'bbb']
    }
    let obj2 = deepClone(obj)
    obj.name = 'hello'
    obj.cars.push('ccc')
    console.log(obj2);
    console.log(obj);
  </script>
</body>

</html>